﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace PP.Basic
{
    public static class AnimationExtension
    {
        private const string Tag = nameof(AnimationExtension);

        public static AnimationClip GetClip(this Animator animator, string clipName)
        {
            AnimationClip clip = null;
            do
            {
                if (animator == null || string.IsNullOrEmpty(clipName))
                    break;

                var clips = animator.runtimeAnimatorController?.animationClips;
                if (clips == null || clips.Length == 0)
                    break;

                for (int i = 0; i < clips.Length; i++)
                {
                    if (clips[i].name == clipName)
                    {
                        clip = clips[i];
                        break;
                    }
                }
            } while (false);

            if (clip == null)
            {
                Debug.LogWarning($"{Tag}.GetClip# clipName: {clipName} not found in {animator.transform}.Animator");
            }
            
            return clip;
        }

        public static float GetClipDuration(this Animator animator, string clipName)
        {
            var clip = animator.GetClip(clipName);
            return clip == null ? 0 : clip.length;
        }

        public static bool HasState(this Animator animator, string stateName, int layerIndex = -1)
        {
            var result = false;
            int stateHash = Animator.StringToHash(stateName);
            if (layerIndex == -1)
            {
                // Check all layers
                for (int i = 0; i < animator.layerCount; i++)
                {
                    if (animator.HasState(i, stateHash))
                    {
                        result = true;
                        break;
                    }
                }
            }
            else
            {
                // Check specific layer
                result = animator.HasState(layerIndex, stateHash);
            }
            return result;
        }
    }
}
